var WxParse = require('../../wxParse/wxParse.js');
var interval = 0;
var page_first_init = true;
var timer = 1;
var fullScreen = false;
var page_first = [];
Page({
    data: {
        WindowWidth: getApp().core.getSystemInfoSync().windowWidth,
        WindowHeight: getApp().core.getSystemInfoSync().windowHeight,
        // WindowHeight: 670,
        IndexBodyTop: '0px',
        scrollHeight: 0,
        startPoint: [0,0],
        mediaBodyLeft: -291,
        startTouch: false,
        mediaItemNum: 3,
        mediaItemShow:{"item1":"dd-media-content-scale","item2":"","item3":"dd-media-content-scale"},
        page_1_rect: {},
        left: 0,
        show_notice: -1,
        animationData: {},
        play: -1,
        time: 0,
        buy: false,
        opendate: false,
        goods: '',
        form: {
            number: 1,
        },
        time_all: [],
        timestamp: getApp().helper.time(),
        show_first_popup: false,
        statusBarH:'', //状态栏高度
        bgcolor:'0'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        getApp().page.onLoad(this, options);
        if (!options.page_id) {
            options.page_id = -1;
        }
        this.setData({
            options: options
        });
        this.loadData(options);

        let self = this;
        // 获取系统信息
        wx.getSystemInfo({
            success:function(e){
                // 获取状态栏高度
                console.log("获取状态栏高度");
                console.log(e);
                self.setData({
                    statusBarH : e.statusBarHeight+4
                })
            }
        })
        /**
        * 会员登录
        */
        getApp().core.login({
          success: function (login_res) {
            var code = login_res.code;
            getApp().request({
              method: 'POST',
              data: { code: code },
              url: getApp().api.passport.wxlogin,
              success: function (res) {
                if (res.code == 0) {
                    //getApp().core.setStorageSync('my_access_token', res.data.access_token);
                    //console.log(res.data.access_token);
                    console.log(res);
                    getApp().setUser(res.data);
                    getApp().core.setStorageSync(getApp().const.ACCESS_TOKEN, res.data.access_token);
                    getApp().trigger.run(getApp().trigger.events.login);
                }
              }
            });
          },
          fail: function (res) {
          },
        });
    },

    show_first_popup: function(){
        var self = this;
        var timestamp = Date.parse(new Date());
        var hide_first_popup = getApp().core.getStorageSync(getApp().const.HIDE_FIRST_POPUP);

        console.log("hide_first_popup=",hide_first_popup);
        if(parseInt(hide_first_popup) > timestamp){
            self.setData({
                show_first_popup: false
            });
        }else{
            self.setData({
                show_first_popup: true
            });
        }
    },

    hide_first_popup: function(){
        console.log("hide_first_popup",11223);
        var self = this;
        var timestamp = Date.parse(new Date());
        //var expiration = timestamp + 1800000; //缓存30分钟
        var expiration = timestamp + 43200000; //缓存12小时
        getApp().core.setStorageSync(getApp().const.HIDE_FIRST_POPUP, expiration);
        self.setData({
            show_first_popup: false
        });
    },

    /**
     * 购买记录
     */
    suspension: function() {
        var self = this;

        interval = setInterval(function() {
            getApp().request({
                url: getApp().api.default.buy_data,
                data: {
                    'time': self.data.time
                },
                method: 'POST',
                success: function(res) {
                    if (res.code == 0) {
                        var inArray = false;
                        var msgHistory = self.data.msgHistory;
                        if (msgHistory == res.md5) {
                            inArray = true;
                        }
                        var cha_time = '';
                        var s = res.cha_time;
                        var m = Math.floor(s / 60 - Math.floor(s / 3600) * 60);
                        if (m == 0) {
                            cha_time = s % 60 + '秒';
                        } else {
                            cha_time = m + '分' + s % 60 + '秒';
                        }

                        if (!inArray && res.cha_time <= 300) {
                            self.setData({
                                buy: {
                                    time: cha_time,
                                    type: res.data.type,
                                    url: res.data.url,
                                    user: (res.data.user.length >= 5) ? res.data.user.slice(0, 4) + "..." : res.data.user,
                                    avatar_url: res.data.avatar_url,
                                    address: (res.data.address.length >= 8) ? res.data.address.slice(0, 7) + "..." : res.data.address,
                                    content: res.data.content,
                                },
                                msgHistory: res.md5
                            });
                        } else {
                            self.setData({
                                buy: false
                            });
                        }

                    }
                },
                noHandlerFail: true,
            });
        }, 10000);
    },

    /**
     * 加载页面数据
     */
    loadData: function() {
        var self = this;
        var data = {};
        var options = self.data.options
        if (options.page_id != -1) {
            data.page_id = options.page_id;
        } else {
            data.page_id = -1;
            var pages_index_index = getApp().core.getStorageSync(getApp().const.PAGE_INDEX_INDEX);
            if (pages_index_index) {
                pages_index_index.act_modal_list = [];
                self.setData(pages_index_index);
            }
        }
        getApp().request({
            url: getApp().api.default.index,
            data: data,
            success: function(res) {
                if (res.code == 0) {
                    var detail = res.data.brand;
                    // WxParse.wxParse("detail", "html", detail, self);
                    console.log("----------------------------------");
                    console.log(detail);
                    self.setData(res.data);
                    console.log("firstpopup=", res.data.firstpopup)
                    if(res.data.firstpopup){
                        self.show_first_popup();
                    }

                    if (res.data.status == 'diy') {
                        var act_modal_list = res.data.act_modal_list;
                        if (options.page_id != -1) {
                            getApp().core.setNavigationBarTitle({
                                title: res.data.info,
                            });
                            self.setData({
                                title: res.data.info
                            });
                        }

                        /*for (var i = act_modal_list.length - 1; i >= 0; i--) {
                            if ((typeof act_modal_list[i].status == 'undefined' || act_modal_list[i].status == 0) && getApp().helper.inArray(act_modal_list[i].page_id, page_first) && !self.data.user_info_show) {
                                act_modal_list.splice(i, 1);
                            } else {
                                page_first.push(act_modal_list[i].page_id);
                            }
                        }*/

                        self.setData({
                            template: res.data.template,
                            act_modal_list: act_modal_list,
                            time_all: res.data.time_all
                        });
                        self.setTime();
                    } else {
                        if (!page_first_init) {
                            res.data.act_modal_list = [];
                        } else {
                            if (!self.data.user_info_show) {
                                page_first_init = false;
                            }
                        }

                        self.setData(res.data);
                        self.miaoshaTimer();
                    }
                    if (options.page_id == -1) {
                        getApp().core.setStorageSync(getApp().const.PAGE_INDEX_INDEX, res.data);
                    }
                }
            },
            complete: function() {
                getApp().core.stopPullDownRefresh();
            }
        });

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        var self = this;
        getApp().page.onShow(this);
        var diy = require('./../../components/diy/diy.js');
        diy.init(this);
        getApp().getConfig(function(config) {
            let store = config.store;
            if (store && store.name && self.data.options.page_id == -1) {
                getApp().core.setNavigationBarTitle({
                    title: store.name,
                });
            }
            if (store && store.purchase_frame === 1) {
                self.suspension(self.data.time);
            } else {
                self.setData({
                    buy_user: '',
                })
            }
        });
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        getApp().getStoreData();
        clearInterval(timer);
        this.loadData();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function(options) {
        getApp().page.onShareAppMessage(this);
        var self = this;
        var user_info = getApp().getUser();
        console.log(user_info);
        var res = {};
        if (self.data.options.page_id != -1) {
            res = {
                path: "/pages/index/index?user_id=" + user_info.id + '&page_id=' + self.data.options.page_id,
                title: self.data.title
            }
        } else {
            res = {
                path: "/pages/index/index?user_id=" + user_info.id,
                title: self.data.store.name
            }
        }

        getApp().request({
            url: "https://wxapp.yzhihe.com/wxappweb/dosignin.html",
            data: {
                my_access_token: user_info.access_token,
                share_page: self.data.options.page_id != -1 ? self.data.options.page_id : 1,
            },
            success: function(res) {
               console.log(res);
            }
        });

        return res;
    },

    showshop: function(e) {

        var self = this;
        var goods_id = e.currentTarget.dataset.id;
        var data = e.currentTarget.dataset;
        getApp().request({
            url: getApp().api.default.goods,
            data: {
                id: goods_id
            },
            success: function(res) {
                if (res.code == 0) {
                    self.setData({
                        data: data,
                        attr_group_list: res.data.attr_group_list,
                        goods: res.data,
                        showModal: true
                    });
                }
            }
        });
    },

    miaoshaTimer: function() {
        var self = this;
        if (!self.data.miaosha) {
            return;
        }
        if (self.data.miaosha.rest_time == 0) {
            return;
        }
        if (self.data.miaosha.ms_next) {} else {
            timer = setInterval(function() {
                if (self.data.miaosha.rest_time > 0) {
                    self.data.miaosha.rest_time = self.data.miaosha.rest_time - 1;
                } else {
                    clearInterval(timer);
                    return;
                }
                self.data.miaosha.times = self.setTimeList(self.data.miaosha.rest_time);
                self.setData({
                    miaosha: self.data.miaosha,
                });
            }, 1000);
        }
    },

    onHide: function() {
        getApp().page.onHide(this);
        this.setData({
            play: -1
        });
        clearInterval(interval);
    },
    onUnload: function() {
        getApp().page.onUnload(this);
        this.setData({
            play: -1
        });
        clearInterval(timer);
        clearInterval(interval);
    },
    showNotice: function(e) {
        console.log(e);
        this.setData({
            show_notice: e.currentTarget.dataset.index
        });
    },
    closeNotice: function() {
        this.setData({
            show_notice: -1
        });
    },

    to_dial: function() {
        var contact_tel = this.data.store.contact_tel;
        getApp().core.makePhoneCall({
            phoneNumber: contact_tel
        })
    },

    closeActModal: function() {
        var self = this;
        var act_modal_list = self.data.act_modal_list;
        for (var i in act_modal_list) {
            var index = parseInt(i);
            if (act_modal_list[index].show) {
                act_modal_list[index].show = false;
            }
            break;
        }
        self.setData({
            act_modal_list: act_modal_list,
        });

        setTimeout(function() {
            for (var i in act_modal_list) {
                if (act_modal_list[i].show) {
                    var one = act_modal_list.splice(i, 1);
                    act_modal_list = one.concat(act_modal_list);
                    break;
                }
            }
            self.setData({
                act_modal_list: act_modal_list
            });
        }, 500);
    },
    naveClick: function(e) {
        var self = this;
        getApp().navigatorClick(e, self);
    },

    /*getScrollHeight: function() { 
        var self = this;
        wx.createSelectorQuery().select('#dd-panel-item1').boundingClientRect((rect) => { console.log(rect),  self.setData({ scrollHeight: rect.height }), console.log(self.data.scrollHeight) }).exec() 
    }, */


    /**
     * 通过判断第一页向下移动超过50，就跳转到第二页
     */
    // getPage1: function() { 
    //     var self = this;
    //     wx.createSelectorQuery().
    //     select('#dd-panel-item1').
    //     boundingClientRect(
    //         (rect) => { 
    //             console.log(rect);  
    //             if (rect.top < -50){
    //                 var windowheight = self.data.WindowHeight;
    //                 this.setData({
    //                     IndexBodyTop: -windowheight+'px',
    //                 })
    //             }else{
    //                 this.setData({ 
    //                     IndexBodyTop: '0px',
    //                 })
    //             }
    //         }).exec() 
    // },

    /**
     * 通过判断第二页向上移动超过50，就跳转到第一页
     */
    // getPage2: function(){
    //     var self = this;
    //     wx.createSelectorQuery()
    //     .select('#dd-panel-item2')
    //     .boundingClientRect(
    //         (rect) => { 
    //             console.log(rect);  
    //             if (rect.top > 50){
    //                 self.setData({ 
    //                     IndexBodyTop: '0px',
    //                 })
    //             }
    //         }).exec() 
    // },

    /**
     * 第一屏触摸开始点
     */
    // mytouchstart: function(e){
    //     this.setData({startPoint: [e.touches[0].pageX, e.touches[0].pageY]});
    // },
    
    /**
     * 第一屏触摸方向
     */
    // mytouchmove: function(e){
    //     self = this;
    //     var curPoint = [e.touches[0].pageX, e.touches[0].pageY];
    //     var startPoint = this.data.startPoint;
    //     if(curPoint[0] <= startPoint[0]){
    //         if(Math.abs(curPoint[0] - startPoint[0]) >= Math.abs(curPoint[1] - startPoint[1])){
    //             //touch left move
    //             console.log(e.timestamp + 'touch left move')
    //             this.setData({
    //                 IndexBodyTop: '0px',
    //             })
    //         }else{
    //             if(curPoint[1] >= startPoint[1]){
    //                 //touch down move
    //                 console.log(e.timestamp + 'touch down move')
    //                 this.setData({
    //                     IndexBodyTop: '0px',
    //                 })
    //             }else{
    //                 //touch up move
    //                 console.log(e.timestamp + 'touch up move')
    //                 this.getPage1()
    //             }
    //         }
    //     }else{
    //         if(Math.abs(curPoint[0] - startPoint[0]) >= Math.abs(curPoint[1] - startPoint[1])){
    //             //touch right move
    //             console.log(e.timestamp + 'touch right move')
    //             this.setData({
    //                 IndexBodyTop: '0px',
    //             })
    //         }else{
    //             if(curPoint[1] >= startPoint[1]){
    //                 //touch down move
    //                 console.log(e.timestamp + 'touch down move')
    //                 this.setData({
    //                     IndexBodyTop: '0px',
    //                 })
    //             }else{
    //                 //touch up move
    //                 console.log(e.timestamp + 'touch up move')
    //                 this.getPage1()
    //             }
    //         }
    //     }
    // },

    /**
     * 第二屏触摸开始点
     */
    // page2touchstart: function(e){
    //     this.setData({startPoint: [e.touches[0].pageX, e.touches[0].pageY]});
    // },
    
    /**
     * 第二屏触摸方向
     */
    // page2touchmove: function(e){
    //     self = this;
    //     var curPoint = [e.touches[0].pageX, e.touches[0].pageY];
    //     var startPoint = this.data.startPoint;
    //     if(curPoint[0] <= startPoint[0]){
    //         if(Math.abs(curPoint[0] - startPoint[0]) >= Math.abs(curPoint[1] - startPoint[1])){
    //             //touch left move
    //             console.log(e.timestamp + 'touch left move')
    //         }else{
    //             if(curPoint[1] >= startPoint[1]){
    //                 //touch down move
    //                 console.log(e.timestamp + 'touch down move')
    //                 this.getPage2()
    //             }else{
    //                 //touch up move
    //                 console.log(e.timestamp + 'touch up move')
    //             }
    //         }
    //     }else{
    //         if(Math.abs(curPoint[0] - startPoint[0]) >= Math.abs(curPoint[1] - startPoint[1])){
    //             //touch right move
    //             console.log(e.timestamp + 'touch right move')
    //         }else{
    //             if(curPoint[1] >= startPoint[1]){
    //                 //touch down move
    //                 console.log(e.timestamp + 'touch down move')
    //                 this.getPage2()
    //             }else{
    //                 //touch up move
    //                 console.log(e.timestamp + 'touch up move')
    //             }
    //         }
    //     }
    // },

    /**
     * 媒体报道触摸开始点
     */
    mediatouchstart: function(e){
        this.setData({startPoint: [e.touches[0].pageX, e.touches[0].pageY]});
    },
    
    /**
     * 媒体报道屏触摸方向
     */
    mediatouchmove: function(e){
        self = this;
        var curPoint = [e.touches[0].pageX, e.touches[0].pageY];
        var startPoint = this.data.startPoint;
        if(curPoint[0] <= startPoint[0]){
            if(Math.abs(curPoint[0] - startPoint[0]) >= Math.abs(curPoint[1] - startPoint[1])){
                //touch left move
                console.log(e.timestamp + 'touch left move1')
                var startTouch = self.data.startTouch;
                if(!startTouch){
                    self.setData({
                        startTouch: true
                    })
                    setTimeout(function(){
                        var curMediaBodyLeft = self.data.mediaBodyLeft;
                        var max = self.data.mediaItemNum * 444;
                        if(curMediaBodyLeft >= -291){
                            var newMediaBodyLeft = curMediaBodyLeft - 444;
                            self.setData({
                                mediaBodyLeft: newMediaBodyLeft
                            })
                        }
                        self.setData({
                            startTouch: false
                        })

                        
                        console.log(newMediaBodyLeft);
                        var point0 = -444 * 0;
                        var point1 = -444 * 1;
                        var point2 = -444 * 2;
                        var point3 = -444 * 3;
                        if(newMediaBodyLeft >= point0){
                            var curMediaItemShow = {"item1":"","item2":"dd-media-content-scale","item3":"dd-media-content-scale"};
                            self.setData({
                                mediaItemShow: curMediaItemShow
                            })
                        }
                        if(newMediaBodyLeft < point0 && newMediaBodyLeft >= point1){
                            var curMediaItemShow = {"item1":"dd-media-content-scale","item2":"","item3":"dd-media-content-scale"};
                            self.setData({
                                mediaItemShow: curMediaItemShow
                            })
                        }
                        if(newMediaBodyLeft < point1 && newMediaBodyLeft >= point2){
                            var curMediaItemShow = {"item1":"dd-media-content-scale","item2":"dd-media-content-scale","item3":""};
                            self.setData({
                                mediaItemShow: curMediaItemShow
                            })
                        }

                    },500)
                }
            
            }else{
                if(curPoint[1] >= startPoint[1]){
                    //touch down move
                    console.log(e.timestamp + 'touch down move')
                }else{
                    //touch up move
                    console.log(e.timestamp + 'touch up move')
                }
            }
        }else{
            if(Math.abs(curPoint[0] - startPoint[0]) >= Math.abs(curPoint[1] - startPoint[1])){
                //touch right move
                console.log(e.timestamp + 'touch right move2')
                var startTouch = self.data.startTouch;
                if(!startTouch){
                    self.setData({
                        startTouch: true
                    })
                    setTimeout(function(){
                        var curMediaBodyLeft = self.data.mediaBodyLeft;

                        var max = self.data.mediaItemNum * 444;
                        if(curMediaBodyLeft < 0){
                            var newMediaBodyLeft = curMediaBodyLeft + 444;
                            self.setData({
                                mediaBodyLeft: newMediaBodyLeft
                            })
                        }
                        self.setData({
                            startTouch: false
                        })

                        console.log(newMediaBodyLeft);
                        var point0 = -444 * 0;
                        var point1 = -444 * 1;
                        var point2 = -444 * 2;
                        var point3 = -444 * 3;
                        if(newMediaBodyLeft >= point0){
                            var curMediaItemShow = {"item1":"","item2":"dd-media-content-scale","item3":"dd-media-content-scale"};
                            self.setData({
                                mediaItemShow: curMediaItemShow
                            })
                        }
                        if(newMediaBodyLeft < point0 && newMediaBodyLeft >= point1){
                            var curMediaItemShow = {"item1":"dd-media-content-scale","item2":"","item3":"dd-media-content-scale"};
                            self.setData({
                                mediaItemShow: curMediaItemShow
                            })
                        }
                        if(newMediaBodyLeft < point1 && newMediaBodyLeft >= point2){
                            var curMediaItemShow = {"item1":"dd-media-content-scale","item2":"dd-media-content-scale","item3":""};
                            self.setData({
                                mediaItemShow: curMediaItemShow
                            })
                        }

                    },500)
                }

            }else{
                if(curPoint[1] >= startPoint[1]){
                    //touch down move
                    console.log(e.timestamp + 'touch down move')
                }else{
                    //touch up move
                    console.log(e.timestamp + 'touch up move')
                }
            }
        }
    },


    onPageScroll: function(e) {
        var self = this;
        // if (fullScreen) {
        //     return;
        // }
        // if (self.data.play != -1) {
        //     var max = getApp().core.getSystemInfoSync().windowHeight;
        //     if (typeof my === 'undefined') {
        //         getApp().core.createSelectorQuery().select('.video').fields({
        //             rect: true
        //         }, function(res) {
        //             if (res.top <= -200 || res.top >= max - 57) {
        //                 self.setData({
        //                     play: -1
        //                 });
        //             }
        //         }).exec();
        //     } else {
        //         getApp().core.createSelectorQuery().select('.video').boundingClientRect().scrollOffset().exec((res) => {
        //             if (res[0].top <= -200 || res[0].top >= max - 57) {
        //                 self.setData({
        //                     play: -1
        //                 });
        //             }
        //         });
        //     }
        // }
        
        var bgcolor = '0';
        console.log('高度');
        console.log(e.scrollTop);
        if(e.scrollTop == 0){
            bgcolor = '0';
        }else if (e.scrollTop >= 0 && e.scrollTop <= 10) {
            bgcolor = '0.1';
        }else if (e.scrollTop >= 10 && e.scrollTop <= 20) {
            bgcolor = '0.1';
        }else if (e.scrollTop > 20 && e.scrollTop <= 30) {
            bgcolor = '0.2';
        }else if (e.scrollTop > 30 && e.scrollTop <= 40) {
            bgcolor = '0.3';
        } else if (e.scrollTop > 40 && e.scrollTop <= 50) {
            bgcolor = '0.4';
        } else if (e.scrollTop > 50 && e.scrollTop <= 60) {
            bgcolor = '0.5';
        } else if (e.scrollTop > 60 && e.scrollTop <= 70) {
            bgcolor = '0.6';
        } else if (e.scrollTop > 70 && e.scrollTop <= 80) {
            bgcolor = '0.7';
        } else if (e.scrollTop > 80 && e.scrollTop <= 90) {
            bgcolor = '0.8';
        } else if (e.scrollTop > 90 && e.scrollTop <= 100) {
            bgcolor = '0.9';
        } else if (e.scrollTop > 100) {
            bgcolor = '1';
        }
        self.setData({
            bgcolor:bgcolor
        })

        
        /*if (e.scrollTop <= 0) {
            // 滚动到最顶部
             e.scrollTop = 0;
        } else if (e.scrollTop > this.data.scrollHeight) {
            // 滚动到最底部
            e.scrollTop = this.data.scrollHeight;
        }
        if (e.scrollTop > this.data.scrollTop || e.scrollTop >= this.data.scrollHeight) {
            //向下滚动 
            console.log('向下 ', this.data.scrollHeight)
            this.setData({
                IndexBodyTop: -self.data.WindowHeight+'px',
            })
        } else {
            //向上滚动 
            console.log('向上滚动 ', this.data.scrollHeight)
        }
           //给scrollTop重新赋值 
        this.setData({
            scrollTop: e.scrollTop
        })
        this.getScrollHeight();
        */


    },

    fullscreenchange: function(e) {
        if (e.detail.fullScreen) {
            fullScreen = true;
        } else {
            fullScreen = false;
        }
    },


});